package com.example.spring_mysql.datascope

import cn.dev33.satoken.stp.StpUtil
import com.mybatisflex.core.constant.SqlConsts
import com.mybatisflex.core.dialect.IDialect
import com.mybatisflex.core.logicdelete.impl.DefaultLogicDeleteProcessor
import com.mybatisflex.core.table.TableInfo
import java.util.*

/**
 * 逻辑删除处理： 填充删除人、 删除时间
 */
class EntityLogicDeleteListener : DefaultLogicDeleteProcessor() {
    override fun buildLogicDeletedSet(logicColumn: String, tableInfo: TableInfo, iDialect: IDialect): String {
        val sqlBuilder = StringBuilder()
        sqlBuilder.append(iDialect.wrap(logicColumn))
            .append(SqlConsts.EQUALS)
            .append(prepareValue(getLogicDeletedValue()))

        val columns = Arrays.asList(*tableInfo.allColumns)

        if (columns.contains(FIELD_DELETE_TIME)) {
            sqlBuilder.append(", ")
                .append(iDialect.wrap(FIELD_DELETE_TIME))
                .append(SqlConsts.EQUALS)
                .append("now()")
        }

        return sqlBuilder.toString()
    }

    companion object {
        private const val FIELD_DELETE_TIME = "delete_time"
        private const val FIELD_DELETE_ID = "delete_id"

        private fun prepareValue(value: Any): Any {
            return if (value !is Number && value !is Boolean) "'$value'" else value
        }
    }
}
